package com.fw.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class AliSmsUtil {


    private static final String accessKeyId = "LTAI5tGbqNEc4Gdwg3djswnX";
    private static final String secret = "qFjb89f5wSTF6J2v8ks68l74GX74iM";


    /**
     * 发送验证码
     *
     * @param phoneNumber
     * @param code
     * @return
     */
    public static boolean send(String phoneNumber, String code) {
        return send(phoneNumber, code, "SMS_228920122");
    }

    private static boolean send(String phoneNumber, String code, String templateCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "贰拾壹度");
        request.putQueryParameter("TemplateCode", templateCode);
        JSONObject templateParam = new JSONObject();
        templateParam.put("code", code);
        request.putQueryParameter("TemplateParam", templateParam.toJSONString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            JSONObject responseJSON = JSONObject.parseObject(response.getData());
            if ("OK".equals(responseJSON.getString("Message"))) {
                return true;
            }
            log.error("【阿里云短信】:发送短信失败，手机号：{},验证码：{},错误信息：{}", phoneNumber, code, responseJSON.getString("Message"));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

/*   public static void main(String[] args) {
        boolean send = AliSmsUtil.send("xxxxxxx", "234s23");
        System.out.println("send = " + send);
    }*/
}
